package org.marketing.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JsonUtils {
	private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    /**
     * @param result 返回值
     * @param key    key值
     * @return 判断集合是否有数据
     */
    public static boolean isArrayThereData(String result, String key) {
        boolean is = false;
        try {
            JSONObject object = new JSONObject(result);
            if (object.has(key)) {
                String data = getJsonStr(result, key);
                if ("".equals(data)) {
                    return false;
                }
                JSONArray array = new JSONArray(data);
                if (array.length() > 0) {
                    is = true;
                }
            } else {
                return false;
            }
        } catch (JSONException e) {
        	logger.error(e.getMessage(),e);
        }
        return is;
    }

    /**
     * @param result json
     * @param key    条数的字段  字段为int型
     * @return 判断 是否有数据 返回
     */
    public static boolean isThereData(String result, String key) {
        boolean is = false;
        try {
            JSONObject jsonObject = new JSONObject(result);
            if ("".equals(jsonObject.get(key) + "")) {
                return false;
            }
            int number = Integer.parseInt(jsonObject.get(key) + "");
            if (number > 0) {
                is = true;
            }
        } catch (JSONException e) {
        	logger.error(e.getMessage(),e);
        }
        return is;
    }


    /**
     * @param result       json
     * @param key          key
     * @param SuccessValue 成功value
     * @return 判断 请求数据是否成功
     */
    public static boolean isSuccess(String result, String key, String SuccessValue) {
        boolean is = false;
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has(key)) {
                String code = jsonObject.getString(key);
                is = SuccessValue.equals(code);
            }
        } catch (JSONException e) {
        	logger.error(e.getMessage(),e);
        }
        return is;
    }

    /**
     * @param result 返回值
     * @param key    key值
     * @return json是否存在key
     */
    public static boolean isHasKey(String result, String key) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has(key)) {
                return true;
            }
        } catch (JSONException e) {
        	logger.error(e.getMessage(),e);
        }
        return false;
    }

    /**
     * @param result 返回值json
     * @param key    key值
     * @return 获取jsonStr的某个字段  只限第一层
     */
    public static String getJsonStr(String result, String key) {
        String jsonStr = "";
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has(key)) {
                jsonStr = jsonObject.getString(key);
            }
        } catch (JSONException e) {
        	logger.error(e.getMessage(),e);
        }
        return jsonStr;
    }
    
    /**
     * json对象转Map<String, Object>
     * @param jsonObject
     * @return
     * @throws JSONException
     */
	@SuppressWarnings("all")
	public static Map<String, Object> json2Map(JSONObject jsonObject) {

		String key;
		Object value;

		Iterator<String> keyIter = jsonObject.keys();
		Map<String, Object> map = new HashMap<String, Object>();

		while (keyIter.hasNext()) {
			key = (String) keyIter.next();
			value = jsonObject.get(key);
			map.put(key, value);
		}
		return map;
	}
	
	/**
	 * 
	 * @param json
	 * @return
	 */
	public static List<Map<String, Object>> jsonArray2List(JSONArray jsonArray) {

		List<Map<String, Object>> list = new ArrayList<>();

		if (jsonArray.length() > 0) {
			for (int i = 0; i < jsonArray.length(); i++) {
				list.add(json2Map(strToJson(jsonArray.get(i).toString())));
			}
		}

		return list;

	}
	

	/**
	 * 字符串转json
	 * 
	 * @param str
	 * @return
	 * @throws JSONException
	 */
	public static JSONObject strToJson(String json) {
		return new JSONObject(json);
	}
	
	/**
	 * Map转化为JSONObject
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static JSONObject map2JsonObject(Map<String, Object> map) {

		JSONObject jsonObj = new JSONObject();

		if (map != null) {

			Iterator<String> it = map.keySet().iterator();

			while (it.hasNext()) {
				String key = it.next();
				jsonObj.put(key, map.get(key));
			}

		}

		return jsonObj;
	}
	//把List<Map<String, Object>>的字符串转换成JsonArray  
    public static String parseListForMapsToJsonArrayStr(List<Map<String, Object>> list) {  
        String jsonArrayStr = null;  
        if(list != null && list.size() != 0) {  
            JSONArray jsonArray = new JSONArray();  
            JSONObject jsonObject = null;  
            Object value = null;  
            for(Map<String, Object> map : list) {  
                jsonObject = new JSONObject();  
                Set<String> set = map.keySet();  
                for(String key : set) {  
                    value = map.get(key);  
                    if(value != null) {  
                        try {  
                            jsonObject.put(key, value.toString());  
                        } catch (JSONException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
                if(jsonObject.length() != 0) {  
                    jsonArray.put(jsonObject);  
                }  
            }  
            jsonArrayStr = jsonArray.toString();  
        }  
          
        return jsonArrayStr;  
    }  
      
    //把Map<String, Object>的字符串转换成JsonObject  
    public static String parseMapToJsonObjectStr(Map<String, Object> map) {  
        String result = null;  
        if(map != null && map.keySet().size() != 0) {  
            Set<String> set = map.keySet();  
            JSONObject jsonObject = new JSONObject();  
            Object value = null;  
            for(String key : set) {  
                value = map.get(key);  
                if(value != null) {  
                    try {  
                        jsonObject.put(key, value.toString());  
                    } catch (JSONException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
            if(jsonObject.length() != 0) {  
                result = jsonObject.toString();  
            }  
        }  
        return result;  
    } 
	/**
     * 将实体POJO转化为JSON
     * @param obj
     * @return
	 * @throws Exception 
     * @throws JSONException
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
	public static String objectToJson(Object obj){
    	JSONObject dest = new JSONObject();
    	Class clzss = obj.getClass();  
    	  
        Field[] fields = clzss.getDeclaredFields();  
  
        for (Field field : fields) {  
        	try {
				dest.put(field.getName(), getFieldValue(obj, field.getName()));
			} catch (JSONException e) {
				logger.error(e.getMessage(),e);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			} 
        }  
        return dest.toString();
    }
    /** 
     * 获取字段的值 
     *  
     * @param data 
     * @param fieldName 
     * @return 
     */  
    @SuppressWarnings("rawtypes")
	public static Object getFieldValue(Object data, String fieldName) throws Exception {  
          
        StringBuilder sb = new StringBuilder();  
          
        Class clzss = data.getClass();  
          
        //将字段首字母大写  
        String firstWord = fieldName.substring(0, 1).toUpperCase();  
        sb.append(firstWord);  
        sb.append(fieldName.substring(1, fieldName.length()));  
  
        final String methodName = "get" + sb.toString();  
  
        Method[] methods = clzss.getDeclaredMethods();  
        for (Method method : methods) { 
            if (methodName.equals(method.getName())) {  
                return method.invoke(data, new Object[] {});  
            }  
        }  
        return null;
    }  
}